﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using BlogKickStart.Models;
using System.ComponentModel.Composition;

namespace BlogKickStart.Controllers
{
	public class UserController : Controller
	{
		public BlogKickstartContext Data { get; set; }
		public UserController() { }

		/// <summary>
		/// This here is used for dependancy injection.  With this, everytime the class gets called, it opens up a new BlogKickstarterContext
		/// </summary>
		/// <param name="data">BlogKickstartContext</param>
		[ImportingConstructor]
		public UserController(BlogKickstartContext data)
		{
			Data = data;
		}

		// GET: /User/Index
		public ActionResult Index()
		{
			return View(Data.Users.ToList());
		}


		//Get: /User/EditUser
		public ActionResult EditUser(int ID)
		{
			return View("EditUser", GetUsers(ID).Single());
		}

		[HttpPost]
		public ActionResult EditUser(User temp)
		{
			Data.Users.Attach(temp);
			Data.SaveChanges();
			return View("EditUser", GetUsers(temp.UserID).Single());
		}


		//Get: /User/DeleteUser
		public ActionResult DeleteUser(int ID)
		{
			return View("DeleteUser", GetUsers(ID).Single());
		}

		//Get: /User/Index
		[HttpPost]
		public ActionResult DeleteUserPost(int userID)
		{
			Data.Users.Remove(Data.Users.Single(n => n.UserID == userID));
			Data.SaveChanges();
			return View("Index", GetUsers());
		}

		//Get: /User/AddUser
		public ActionResult AddUser()
		{
			return View("AddUser");
		}

		[HttpPost]
		public ActionResult AddUser(User newUser)
		{

			if (ModelState.IsValid)
			{
				//var users = new List<User>();
				//users = GetUsers().ToList<User>();

				//int nextVal = users.Any() ? users.Max(n => (int)n.UserID) + 1 : 1;
				//newUser.UserID = nextVal;
				Data.Users.Add(newUser);

				try
				{
					Data.SaveChanges();
				}
				catch (Exception e)
				{
					string s = e.ToString();
				}
			}
			return View("Index", GetUsers());
		}

		//Get: /User/DetailsUser
		public ActionResult DetailsUser(int ID)
		{
			return View("DetailsUser", GetUsers(ID).Single());
		}


		public IQueryable<User> GetUsers(int? userId = null)
		{
			IQueryable<User> temp = Data.Users;
			if (userId != null)
				temp = temp.Where(n => n.UserID == userId.Value);
			return temp;
		}

	}
}
